#include "gateway_taskpool.h"
#include <boost/interprocess/detail/atomic.hpp>

boost::uint32_t gateway_taskpool::_lock_state = NULL;
gateway_taskpool* gateway_taskpool::_task_pool = NULL;

gateway_taskpool::gateway_taskpool()
: _thread_count(0){
}

gateway_taskpool* gateway_taskpool::get_instance(){
	if (NULL == _task_pool) {
		while (boost::interprocess::ipcdetail::atomic_cas32(&_lock_state, 1, 0));
		if (NULL == _task_pool) {
			_task_pool = new gateway_taskpool();
		}
		boost::interprocess::ipcdetail::atomic_cas32(&_lock_state, 0, 1);
	}

	return _task_pool;
}

bool gateway_taskpool::start(){
	_thread_count = boost::thread::hardware_concurrency() * 2;
	return adjust(_thread_count);
}

bool gateway_taskpool::stop(){
	_thread_count = 0;
	_threadpool.clear();
	_threadpool.wait();
	return _threadpool.size_controller().resize(_thread_count);
}

void gateway_taskpool::cancel(){
	_threadpool.clear();
}

bool gateway_taskpool::adjust(unsigned int thread_size){
	return _threadpool.size_controller().resize(thread_size);
}

bool gateway_taskpool::schedule(gateway_task_ptr task, void* param){
	if (_thread_count == 0) {
		return false;
	}
		
	return _threadpool.schedule(boost::bind(&gateway_task::on_task, task, param));
}